package models.admin;

import models.BaseModel;
import models.constants.AvailableStatus;
import play.modules.paginate.JPAExtPaginator;

import javax.persistence.*;
import java.util.List;
import java.util.Map;

/**
 * Created by liming on 16/7/4.
 */
@Entity
@Table(name = "admin_role")
public class AdminRole extends BaseModel{
    /**
     * 角色编号
     */
    @Column(name = "code")
    public String code;
    /**
     * 角色名称
     */
    @Column(name = "name")
    public String name;

    /**
     * 菜单ID
     */
    @Column(name = "menu_id")
    public Long menuId;

    /**
     * 当前状态  禁用\可用
     *  AVAILABLE("启用"),
     *  FREEZE("禁用");
     */
    @Column(name = "available_status")
    @Enumerated(EnumType.STRING)
    public AvailableStatus status;

    /**
     * 备注
     */
    @Column(name = "remark")
    public String remark;


    /**
     * 分页查询.
     */
    public static JPAExtPaginator<AdminRole> findByCondition(Map<String, Object> conditionMap, String orderByExpress, int pageNumber, int pageSize){
        // 拼接sql
        StringBuilder xsqlBuilder = new StringBuilder(" 1 = 1 ")
                .append("/~ and t.id = {id} ~/")
                .append("/~ and t.code like {code} ~/") //编号
                .append("/~ and t.name like {name} ~/"); //名称

        util.xsql.XsqlBuilder.XsqlFilterResult result = new util.xsql.XsqlBuilder().generateHql(xsqlBuilder.toString(), conditionMap);
        JPAExtPaginator<AdminRole> orderPage = new JPAExtPaginator<>("AdminRole t", "t", AdminRole.class,
                result.getXsql(), conditionMap).orderBy(orderByExpress);
        orderPage.setPageNumber(pageNumber);
        orderPage.setPageSize(pageSize);
        orderPage.setBoundaryControlsEnabled(false);
        return orderPage;
    }

    /**
     * 获取所有启用状态的角色
     * @return
     */
    public static List<AdminRole> loadRoleList(){
        return AdminRole.find("status = ?" , AvailableStatus.AVAILABLE).fetch();
    }

    //判断某菜单是否被使用
    public static Long countByMenu(long menuId){
        return AdminRole.count("menuId = ? " , menuId );
    }

    //判断角色是否被使用
    public static Boolean checkIsUsed(long id){
        //角色业务关联表
        long roleOperateNum = AdminRoleOperate.count(" adminRole.id = ?",id);
        if(roleOperateNum > 0)
            return true;
        //用户角色关联表
        long userRoleNum = AdminUserRole.count(" adminRole.id = ?" , id);
        if(userRoleNum > 0)
            return true;
        return false;
    }





}
